package com.netpace.iem.umair.dal;

import java.util.ArrayList;
import java.util.List;

import com.netpace.iem.umair.model.Category;

import org.apache.log4j.Logger;

public class CategoryMemory implements ICategoryDao {
	private List<Category> categories;
	static Logger log = Logger.getLogger(CategoryMemory.class.getName());

	// Default constructor is for Main memory Db
	public CategoryMemory() {
		log.debug("Main Memory DB Selected");
		this.categories = new ArrayList<Category>();
	}

	@Override
	public void insert(Category category){
		categories.add(category);
		log.debug("1 record inserted");
	}
	
	@Override
	public void update(Category category, int pk) {
		int index = getIndex(pk);
		if ( index != -1 ) {
			categories.remove(index);
			categories.add(index, category);
			log.debug("1 record updated");
		}
	}
	
	@Override
	public void delete(Category category, int pk) {
		int index = getIndex(category); 
		if ( index != -1 ) {
			categories.remove(index);
			log.debug("1 record deleted");
		}
	}
	
	@Override
	public void delete(int pk) {
		int index = getIndex(pk); 
		if ( index != -1 ) {
			categories.remove(index);
			log.debug("1 record deleted");
		}
	}
	
	@Override
	public Category findById(int pk) {
		int index = getIndex(pk); 
		
		if ( index != -1 ) {
			log.debug("returning the record found");
			return categories.get(index);
		}
		
		return null;
	}
	
	@Override
	public List<Category> findAll(){
		log.debug("returning the records found");
		return categories;
	}
	
	private int getIndex(Category category) {
		if ( categories.contains(category) ) 
			return categories.indexOf(category);
		else
			return -1;
	}
	
	private int getIndex(int pk) {
		for (int i = 0; i < categories.size(); i++) {
			if ( categories.get(i).getId() == pk ) {
				return i;
			}
		}
		
		return -1;
	}

}
